package project

import (
	"context"
	"git.mycaigou.com/gfyx/common/http_client"
	"git.mycaigou.com/gfyx/common/simplecopier"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto"
	projectDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/project"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/constants"
	bigdataDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/bigdata"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/dto/opensearch"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/repository/business_opportunity"
	businessOpportunityPb "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/business_opportunity"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/business_opportunity/project"
	"git.myscrm.cn/golang/stark/v4"
	"strings"
)

type SearchProjectRepository struct {
}

// 找项目
func NewSearchProjectRepository() project.SearchProjectRepositoryIface {
	return &SearchProjectRepository{}
}

// 通用调用建模接口
func (r *SearchProjectRepository) CommonSearch(ctx context.Context, path string, params map[string]interface{}) (map[string]interface{}, error) {
	v := map[string]interface{}{}

	//path := "http://localhost:8080/pub/40220901/searchTakenLandPub/searchTakenLand"
	header := map[string]string{}
	_, _, errs := http_client.NewGfyxModelApiHttpClient().Post(ctx, path, params, header).EndStruct(&v)
	if len(errs) > 0 {
		return nil, errs[0]
	}

	return v, nil
}

/************  分割线，链路优化  *************/

// 在建项目
func (r *SearchProjectRepository) MohurdProjectList(ctx context.Context, param *opensearch.MohurdProjectListRequest) (interface{}, error) {
	//调用opensearch接口
	paramMap, _ := simplecopier.StructToMapByJsonTag(param)
	resultData := &http_client.OpenSearchResponse{}
	_, _, errs := http_client.NewOpenSearchHttpClient().Get(ctx, constants.OpenSearchApiPathMohurdProject, paramMap).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	//数据预处理
	developerCreditCode := make([]string, 0)
	idList := make([]string, 0)
	for _, item := range resultData.Data.List {
		itemV, err := r.processMohurdProject(ctx, item)
		if err != nil {
			stark.Logger.Errorf(ctx, "在建项目预处理,错误信息:%v", err)
		}
		item = itemV

		if item["organizing_code"] != nil {
			developerCreditCode = append(developerCreditCode, item["organizing_code"].(string))
		}

		if item["id"] != nil {
			idList = append(idList, item["id"].(string))
		}

	}
	//todo 获取开发商联系人数量（按线索雷达的联系人）
	for _, projectValue := range resultData.Data.List {
		projectValue["contact_num"] = 0
	}

	//数据状态
	opptyStatusParam := &businessOpportunityPb.GetOpptyStatusBatchRequest{
		DataSource:   constants.DataSourceBuilding,
		DataSourceId: idList,
	}
	opptyStatus, err := business_opportunity.NewOpptyStatusRepository().GetOpptyStatusBatch(ctx, opptyStatusParam)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetOpptyStatusBatch接口异常:%s,错误信息:%s", err)
	}
	for _, item := range resultData.Data.List {
		for _, opptyValue := range opptyStatus.List {
			if item["id"] != nil && item["id"] == opptyValue.DataSourceId {
				item["oppty_status"] = opptyValue.StatusName
			}
		}
		if item["oppty_status"] == nil {
			item["oppty_status"] = ""
		}
	}

	return resultData, nil
}

func (r *SearchProjectRepository) processMohurdProject(ctx context.Context, projectData map[string]interface{}) (map[string]interface{}, error) {
	if projectData["build_corp_name"] != nil { //建设单位，存在多个
		buildCorpNameArr := strings.Split(projectData["build_corp_name"].(string), ",")
		if len(buildCorpNameArr) > 1 {
			projectData["isMultiDeveloper"] = 1
		} else {
			projectData["isMultiDeveloper"] = 0
		}
	}
	if projectData["company_type_label"] != nil {
		projectData["company_type_label_string"] = projectData["company_type_label"].(string)
		projectData["company_type_label"] = strings.Split(projectData["company_type_label"].(string), ",")
	}

	if projectData["top_company_type_label"] != nil {
		projectData["top_company_type_label_string"] = projectData["top_company_type_label"].(string)
		projectData["top_company_type_label"] = strings.Split(projectData["top_company_type_label"].(string), ",")
	}

	if projectData["organizing_code"] != nil {
		OrganizingCodeArr := strings.Split(projectData["organizing_code"].(string), ",")
		if len(OrganizingCodeArr) > 0 {
			projectData["organizing_code_arr"] = OrganizingCodeArr
			projectData["organizing_code"] = OrganizingCodeArr[0]
		}

	}

	if projectData["top_organizing_code"] != nil {
		topOrganizingCodeArr := strings.Split(projectData["top_organizing_code"].(string), ",")
		if len(topOrganizingCodeArr) > 0 {
			projectData["top_organizing_code_arr"] = topOrganizingCodeArr
			projectData["top_organizing_code"] = topOrganizingCodeArr[0]
		}
	}

	if projectData["begin_date"] != nil && len(projectData["begin_date"].(string)) >= 10 {
		projectData["begin_date"] = projectData["begin_date"].(string)[0:10]
	}
	if projectData["end_date"] != nil && len(projectData["end_date"].(string)) >= 10 {
		projectData["end_date"] = projectData["end_date"].(string)[0:10]
	}
	if projectData["contract_date"] != nil && len(projectData["contract_date"].(string)) >= 10 {
		projectData["contract_date"] = projectData["contract_date"].(string)[0:10]
	}
	if projectData["prj_approval_date"] != nil && len(projectData["prj_approval_date"].(string)) >= 10 {
		projectData["prj_approval_date"] = projectData["prj_approval_date"].(string)[0:10]
	}
	if projectData["release_date"] != nil && len(projectData["release_date"].(string)) >= 10 {
		projectData["release_date"] = projectData["release_date"].(string)[0:10]
	}
	if projectData["tender_result_date"] != nil && len(projectData["tender_result_date"].(string)) >= 10 {
		projectData["tender_result_date"] = projectData["tender_result_date"].(string)[0:10]
	}
	if projectData["b_date"] != nil && len(projectData["b_date"].(string)) >= 10 {
		projectData["b_date"] = projectData["b_date"].(string)[0:10]
	}
	if projectData["e_date"] != nil && len(projectData["e_date"].(string)) >= 10 {
		projectData["e_date"] = projectData["e_date"].(string)[0:10]
	}

	return projectData, nil
}

// 在建项目详情
func (r *SearchProjectRepository) ProjectDetail(ctx context.Context, param *dto.CommonIdRequest) (interface{}, error) {
	//调用数芯接口
	paramMap, _ := simplecopier.StructToMapByJsonTag(param)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathMohurdProjectList, paramMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	if len(resultData.Data.Rows) <= 0 {
		return nil, nil
	}
	//数据预处理
	for _, item := range resultData.Data.Rows {
		itemV, err := r.processMohurdProject(ctx, item)
		if err != nil {
			stark.Logger.Errorf(ctx, "在建项目预处理,错误信息:%v", err)
		}
		//数据状态
		if item["id"] != nil {
			param := &businessOpportunityPb.GetOpptyStatusRequest{
				DataSource: constants.DataSourceBuilding,
				//DataSourceId: strconv.FormatFloat(item["id"].(float64), 'f', 0, 64),
				DataSourceId: item["id"].(string),
				FromDevice:   constants.FromDeviceClueMini,
				DetailPage:   true,
			}
			opptyStatus, err := business_opportunity.NewOpptyStatusRepository().GetOpptyStatus(ctx, param)
			if err != nil {
				stark.Logger.Errorf(ctx, "获取oppty_status，err:%+v", err)
			}

			item["oppty_status"] = opptyStatus.StatusName
		}

		item = itemV
	}

	return resultData.Data.Rows[0], nil
}

// 在建项目详情 - 参与单位
func (r *SearchProjectRepository) AboutCompany(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathAboutCompany, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}

	return resultData, nil
}

// 在建项目详情 - 招投标
func (r *SearchProjectRepository) BiddingList(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathBiddingList, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, item := range resultData.Data.Rows {
		if item["tender_result_date"] != nil && len(item["tender_result_date"].(string)) >= 10 {
			item["tender_result_date"] = item["tender_result_date"].(string)[0:10]
		}
	}
	return resultData, nil
}

// 在建项目详情 - 合同登记
func (r *SearchProjectRepository) Contract(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathContract, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, item := range resultData.Data.Rows {
		if item["contract_date"] != nil && len(item["contract_date"].(string)) >= 10 {
			item["contract_date"] = item["contract_date"].(string)[0:10]
		}
	}
	return resultData, nil
}

// 在建项目详情 - 施工图审
func (r *SearchProjectRepository) Construction(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathConstruction, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, item := range resultData.Data.Rows {
		if item["censor_e_date"] != nil && len(item["censor_e_date"].(string)) >= 10 {
			item["censor_e_date"] = item["censor_e_date"].(string)[0:10]
		}

		if item["one_censor_is_pass"] != nil && item["one_censor_is_pass"].(float64) == 1 {
			item["one_censor_is_pass"] = "是"
		} else {
			item["one_censor_is_pass"] = "否"
		}
	}
	return resultData, nil
}

// 在建项目详情 - 施工许可
func (r *SearchProjectRepository) License(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathLicense, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, item := range resultData.Data.Rows {
		if item["release_date"] != nil && len(item["release_date"].(string)) >= 10 {
			item["release_date"] = item["release_date"].(string)[0:10]
		}
	}
	return resultData, nil
}

// 在建项目详情 - 竣工备案
func (r *SearchProjectRepository) CompletionRecord(ctx context.Context, param *projectDto.ProjectDetailRequest) (interface{}, error) {
	//调用数芯接口
	bigDataParam := bigdataDto.ProjectDetailRequest{}
	//结构体copy
	err := simplecopier.CopyToStruct(&bigDataParam, param)
	if err != nil {
		stark.Logger.Errorf(ctx, "结构体copy失败，err:%+v", err)
	}
	bigDataParamMap, _ := simplecopier.StructToMapByJsonTag(bigDataParam)
	resultData := &http_client.BigDataResponse{}
	_, _, errs := http_client.NewBigdataApiHttpClient().Post(ctx, constants.BigDataPathCompletionRecord, bigDataParamMap, map[string]string{}).EndStruct(&resultData)
	if len(errs) > 0 {
		return nil, errs[0]
	}
	for _, item := range resultData.Data.Rows {
		if item["b_date"] != nil && len(item["b_date"].(string)) >= 10 {
			item["b_date"] = item["b_date"].(string)[0:10]
		}
		if item["e_date"] != nil && len(item["e_date"].(string)) >= 10 {
			item["e_date"] = item["e_date"].(string)[0:10]
		}
	}
	return resultData, nil
}
